﻿using Kinlo.Entitys;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Services.Context;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;
using XingLucifer.IBase.Models.PLCInteraktion;

namespace UIWindows.Services.Handle
{
    [Attributes.TaskClass(TaskTypes.PLC清除记忆)]
    public class MemoryClearing : ServierBase
    {
        public MemoryClearing(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig, UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic, MesParameterStatic mesParameterStatic) : 
            base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic, mesParameterStatic)
        {

        }

        public override Task Handle(DataContext context)
        {
            if (!ClearSignal(context)) { return Task.CompletedTask; }
            try
            {
                var plc = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == context.ServiceName && x.TaskType == TaskTypes.扫描信号).Communication as OmronCIP;
                List<long> list = new List<long>();
                IDArrayModel iDArrayModel = null;
                if (context.Struct_Length > 100)
                {
                    if (context.Struct_Length != 128 && context.Struct_Length != 256)
                    {
                        "请注意，记忆清除长度请填写为2的正数倍！！！".MessageDialogs(MessageLevelType.警告, hostDialog: Enums.PopUpTypes.Global);
                        return base.Handle(context);
                    }
                    for (int i = 0; i < 3; i++)
                    {
                        int address = 0;
                        switch (context.Struct_Length)
                        {
                            case 128:
                                address = i * 400;
                                iDArrayModel = new IDArrayModel(i < 1 ? 100 : 56);
                                break;
                            case 256:
                                address = i * 400;
                                iDArrayModel = new IDArrayModel(i < 2 ? 100 : 56);
                                break;
                        }
                        //plc.ReadClass(context.Address_Struct + address, iDArrayModel);
                        list.AddRange(iDArrayModel.ID.Where(x => x != 0));
                        if (list.Count == 128)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    iDArrayModel = new IDArrayModel(context.Struct_Length);
                    plc.ReadClass(context.Address_Struct, iDArrayModel);
                    list.AddRange(iDArrayModel.ID.Where(x => x != 0));
                }
                RunLog($"ID：[{string.Join('-', list)}]");
                Parallel.ForEach(list, snowflakeId =>
                {
                    DateTime dateTime = DateTime.Now;
                    ProductionData? entity = _temporaryStatic.EntityCache.FirstOrDefault(x => x.SnowflakeId == snowflakeId);
                    if (entity == null)
                    {
                        RunLog($"实体缓存查询不到==>[{snowflakeId}]，转到数据库查询");
                        entity = dateTime.GetEntity(context.TaskType, snowflakeId);
                        if (entity == null)
                        {
                            RunLog($"数据库找不到ID为：{snowflakeId}");
                            return;
                        }
                    }
                    else
                    {
                        ProductionData.Meta.TableName = entity.Items["TableName"].ToString();
                    }
                    try
                    {
                        entity.ResultTotal = ResultTypes.人工清除记忆;
                        entity.Update();
                    }
                    catch (Exception ex)
                    {
                        RunLog($"数据库保存异常：{ex}");
                    }
                });
            }
            catch (Exception ex)
            {
                RunLog($"异常：{ex}");
            }
            return base.Handle(context);
        }
    }
}
